#include "precomp.h"
#include "jmutex.h"
#include "jmutex_p.h"

// - class JMutex -

/**
 * @brief JMutex::JMutex
 * @param mode
 */
JMutex::JMutex(JMutex::RecursionMode mode)
{
    d = new JMutexPrivate(mode);
}

/**
 * @brief JMutex::~JMutex
 */
JMutex::~JMutex()
{
    delete d;
}

/**
 * @brief JMutex::lock
 */
void JMutex::lock()
{
    if (d->ref) {
        d->ref->lock();
    } else {
        d->mutex.lock();
    }
}

/**
 * @brief JMutex::tryLock
 * @param timeout
 * @return
 */
bool JMutex::tryLock(int timeout)
{
    if (d->ref) {
        return d->ref->tryLock(timeout);
    } else {
        return d->mutex.tryLock(timeout);
    }
}

/**
 * @brief JMutex::unlock
 */
void JMutex::unlock()
{
    if (d->ref) {
        d->ref->unlock();
    } else {
        d->mutex.unlock();
    }
}

JMutex::JMutex(const JMutex &other)
{
    d = other.d;
}

JMutex &JMutex::operator=(const JMutex &other)
{
    d = other.d;
    return *this;
}

/**
 * @brief JMutex::JMutex
 * @param other
 */
JMutex::JMutex(QMutex *other)
{
    d = new JMutexPrivate(other);
}

/**
 * @brief JMutex::mutex
 * @return
 */
QMutex *JMutex::mutex() const
{
    if (d->ref) {
        return d->ref;
    } else {
        return &d->mutex;
    }
}

// - class JMutexLocker -

/**
 * @brief JMutexLocker::JMutexLocker
 * @param mutex
 */
JMutexLocker::JMutexLocker(JMutex *mutex)
{
    d = new JMutexLockerPrivate(mutex);
}

/**
 * @brief JMutexLocker::~JMutexLocker
 */
JMutexLocker::~JMutexLocker()
{
    delete d;
}

/**
 * @brief JMutexLocker::unlock
 */
void JMutexLocker::unlock()
{
    d->locker.unlock();
}

/**
 * @brief JMutexLocker::relock
 */
void JMutexLocker::relock()
{
    d->locker.relock();
}

JMutex JMutexLocker::mutex() const
{
    return JMutex(d->locker.mutex());
}
